//
//  LZImageLoader.m
//  Project
//
//  Created by liting on 2025/8/29.
//

#import "LZImageLoader.h"

@interface LZImageLoader ()

@property (nonatomic, strong) SDWebImageManager *imageManager;

@end

@implementation LZImageLoader

#pragma mark - 单例
+ (instancetype)sharedLoader {
    static LZImageLoader *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _imageManager = [SDWebImageManager sharedManager];

        // 默认配置
        [self setupDefaultConfig];
    }
    return self;
}

- (void)setupDefaultConfig {
    // 设置最大并发下载数
    [SDWebImageDownloader sharedDownloader].config.maxConcurrentDownloads = 6;

    // 设置超时时间
    [SDWebImageDownloader sharedDownloader].config.downloadTimeout = 15.0;

    // 设置缓存配置
    SDImageCacheConfig *cacheConfig = [SDImageCache sharedImageCache].config;
    cacheConfig.maxMemoryCost = 1024 * 1024 * 100; // 100MB内存缓存
    cacheConfig.maxDiskSize = 1024 * 1024 * 500;   // 500MB磁盘缓存
    cacheConfig.maxDiskAge = 60 * 60 * 24 * 7;     // 7天缓存时间
}

#pragma mark - 图片加载方法
- (void)loadImageWithURLString:(NSString *)urlString
                    completion:(LZImageCompletionBlock)completion {

    [self loadImageWithURLString:urlString
                    placeholder:nil
                  intoImageView:nil
                        options:0
                       progress:nil
                     completion:completion];
}

- (void)loadImageWithURLString:(NSString *)urlString
                  placeholder:(UIImage *)placeholder
                intoImageView:(UIImageView *)imageView
                    completion:(LZImageCompletionBlock)completion {

    [self loadImageWithURLString:urlString
                    placeholder:placeholder
                  intoImageView:imageView
                        options:0
                       progress:nil
                     completion:completion];
}

- (void)loadImageWithURLString:(NSString *)urlString
                  placeholder:(UIImage *)placeholder
                intoImageView:(UIImageView *)imageView
                     progress:(LZImageProgressBlock)progress
                    completion:(LZImageCompletionBlock)completion {

    [self loadImageWithURLString:urlString
                    placeholder:placeholder
                  intoImageView:imageView
                        options:0
                       progress:progress
                     completion:completion];
}

- (void)loadImageWithURLString:(NSString *)urlString
                  placeholder:(UIImage *)placeholder
                intoImageView:(UIImageView *)imageView
                       options:(SDWebImageOptions)options
                     progress:(LZImageProgressBlock)progress
                    completion:(LZImageCompletionBlock)completion {

    if (!urlString || urlString.length == 0) {
        if (completion) {
            NSError *error = [NSError errorWithDomain:@"LZImageLoaderErrorDomain"
                                                 code:-1
                                             userInfo:@{NSLocalizedDescriptionKey: @"URL字符串为空"}];
            completion(nil, error, LZImageCacheTypeNone, nil);
        }
        return;
    }

    NSURL *url = [NSURL URLWithString:urlString];
    if (!url) {
        if (completion) {
            NSError *error = [NSError errorWithDomain:@"LZImageLoaderErrorDomain"
                                                 code:-2
                                             userInfo:@{NSLocalizedDescriptionKey: @"URL格式错误"}];
            completion(nil, error, LZImageCacheTypeNone, nil);
        }
        return;
    }

    // 如果有imageView，使用SDWebImage的category方法
    if (imageView) {
        SDWebImageContext *context = nil;

        [imageView sd_setImageWithURL:url
                     placeholderImage:placeholder
                              options:options
                              context:context
                             progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            if (progress) {
                progress(receivedSize, expectedSize, targetURL);
            }
        } completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            if (completion) {
                LZImageCacheType lzCacheType = [self convertSDCacheTypeToLZCacheType:cacheType];
                completion(image, error, lzCacheType, imageURL);
            }
        }];
    } else {
        // 没有imageView，直接使用manager下载
        [self.imageManager loadImageWithURL:url
                                   options:options
                                  progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            if (progress) {
                progress(receivedSize, expectedSize, targetURL);
            }
        } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
            if (completion && finished) {
                LZImageCacheType lzCacheType = [self convertSDCacheTypeToLZCacheType:cacheType];
                completion(image, error, lzCacheType, imageURL);
            }
        }];
    }
}

#pragma mark - 图片下载方法
- (void)downloadImageWithURLString:(NSString *)urlString
                        completion:(LZImageDownloadCompletionBlock)completion {

    [self downloadImageWithURLString:urlString
                            progress:nil
                          completion:completion];
}

- (void)downloadImageWithURLString:(NSString *)urlString
                          progress:(LZImageProgressBlock)progress
                        completion:(LZImageDownloadCompletionBlock)completion {

    if (!urlString || urlString.length == 0) {
        if (completion) {
            NSError *error = [NSError errorWithDomain:@"LZImageLoaderErrorDomain"
                                                 code:-1
                                             userInfo:@{NSLocalizedDescriptionKey: @"URL字符串为空"}];
            completion(nil, nil, error, YES);
        }
        return;
    }

    NSURL *url = [NSURL URLWithString:urlString];
    if (!url) {
        if (completion) {
            NSError *error = [NSError errorWithDomain:@"LZImageLoaderErrorDomain"
                                                 code:-2
                                             userInfo:@{NSLocalizedDescriptionKey: @"URL格式错误"}];
            completion(nil, nil, error, YES);
        }
        return;
    }

    [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:url
                                                          options:0
                                                         progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
        if (progress) {
            progress(receivedSize, expectedSize, targetURL);
        }
    } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
        if (completion) {
            completion(image, data, error, finished);
        }
    }];
}

#pragma mark - 缓存管理
- (NSUInteger)getCacheSize {
    return [[SDImageCache sharedImageCache] totalDiskSize];
}

- (void)clearMemoryCache {
    [[SDImageCache sharedImageCache] clearMemory];
}

- (void)clearDiskCache {
    [[SDImageCache sharedImageCache] clearDiskOnCompletion:nil];
}

- (void)clearAllCache {
    [[SDImageCache sharedImageCache] clearMemory];
    [[SDImageCache sharedImageCache] clearDiskOnCompletion:nil];
}

- (void)clearExpiredCache {
    [[SDImageCache sharedImageCache] deleteOldFilesWithCompletionBlock:nil];
}

- (BOOL)isImageCachedForURLString:(NSString *)urlString {
    if (!urlString) return NO;
    NSURL *url = [NSURL URLWithString:urlString];
    return [self.imageManager cacheKeyForURL:url] != nil;
}

#pragma mark - 工具方法
- (UIImage *)getCachedImageForURLString:(NSString *)urlString {
    if (!urlString) return nil;
    NSURL *url = [NSURL URLWithString:urlString];
    NSString *key = [self.imageManager cacheKeyForURL:url];
    return [[SDImageCache sharedImageCache] imageFromCacheForKey:key];
}

- (void)preloadImages:(NSArray<NSString *> *)urlStrings {
    for (NSString *urlString in urlStrings) {
        if (urlString.length > 0) {
            NSURL *url = [NSURL URLWithString:urlString];
            if (url) {
                [self.imageManager loadImageWithURL:url options:SDWebImagePreloadAllFrames progress:nil completed:nil];
            }
        }
    }
}

- (void)cancelImageLoadForImageView:(UIImageView *)imageView {
    [imageView sd_cancelCurrentImageLoad];
}

- (void)setMaxConcurrentDownloads:(NSInteger)count {
    [SDWebImageDownloader sharedDownloader].config.maxConcurrentDownloads = count;
}

- (void)setDownloadTimeout:(NSTimeInterval)timeout {
    [SDWebImageDownloader sharedDownloader].config.downloadTimeout = timeout;
}

#pragma mark - 私有方法
- (LZImageCacheType)convertSDCacheTypeToLZCacheType:(SDImageCacheType)sdCacheType {
    switch (sdCacheType) {
        case SDImageCacheTypeNone:
            return LZImageCacheTypeNone;
        case SDImageCacheTypeDisk:
            return LZImageCacheTypeDisk;
        case SDImageCacheTypeMemory:
            return LZImageCacheTypeMemory;
        case SDImageCacheTypeAll:
            return LZImageCacheTypeMemory; // 多个缓存时返回内存缓存类型
        default:
            return LZImageCacheTypeNone;
    }
}

@end
